<?php

namespace App\Jobs;

use App\Services\GetFlvService;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class BiliBiliVideoDownloadJob extends Job
{

    protected $page ;
    protected $saveInfo = [
      'extension' => 'flv',
      'file_name' => '',
      'save_folder' => ''
    ];
    public function __construct($page)
    {
        $this->page = $page;
    }


    public function handle()
    {

        $this->saveInfo['save_folder'] = storage_path().'/bili/'.$this->page->bvid;
        $this->saveInfo['file_name'] = str_replace('/','',$this->page->part);

        if(! is_dir( $this->saveInfo['save_folder']))
        mkdir($this->saveInfo['save_folder'],0700,true);

        $flvService = new GetFlvService($this->page->bvid,$this->page->cid);
        $flvUrls = $flvService->get();


        foreach ($flvUrls as $index => $flvUrl)
        $this->downLoad($flvUrl->url,
            $this->saveInfo['save_folder'].'/'.$this->saveInfo['file_name']. $index . $this->saveInfo['extension']
        );

        //查询所有分割文件
        $files = glob(
            $this->saveInfo['save_folder'].'/'.$this->saveInfo['file_name'].'*'.$this->saveInfo['extension']
        );

        //合并flv
	dispatch(new FlvMergeJob($files,$this->saveInfo['save_folder'].'/'.$this->saveInfo['file_name']
		.$this->saveInfo['extension'] ));
	dd("X");
    }

    protected function downLoad($flvUrl,$file_save_path)
    {
        if( file_exists($file_save_path))
        return true;

        $client = new Client(['verify' => false]);
        $param = parse_url($flvUrl);
        $host = $param['host'];
        $client->get($flvUrl,['save_to' => $file_save_path,
            'headers' => [
                'Host' => $host,
                "User-Agent" => 'Chrome/49.0.2587.3',
                'Accept' => '*',
                'Accept-Encoding' => 'gzip',
                'Referer' => 'http://www.bilibili.com/video/'.$this->page->bvid,
                'Origin' => 'https://www.bilibili.com'
        ]]);


        Log::info($file_save_path.' 下载完成');
    }

}
